<template>
  <div>
    <!--搜索框-->
    <el-form :inline="true" :model="searchForm">
      <el-form-item>
        <el-input v-model="searchForm.name" placeholder="图书名称" clearable @clear="getList"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="select">搜索</el-button>
        <el-button type="primary" @click="saveHandle" v-if="hasAuth('book:manage:save')">新增</el-button>

        <el-popconfirm title="确定要删除这些记录吗？" @confirm="delHandle(null)" style="margin-left: 10px;"
                       v-if="hasAuth('book:manage:delete')">
          <el-button type="danger" slot="reference" :disabled="delBtnStu">批量删除</el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>

    <!--列表-->
    <el-table ref="multipleTable" border stripe :data="tableData" tooltip-effect="dark" style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column v-if="!this.user" width="55px" type="selection"></el-table-column>
      <el-table-column prop="name" label="书籍名称"></el-table-column>
      <el-table-column prop="isbn" label="ISBN码" width="150"></el-table-column>
      <el-table-column prop="typeName" label="类别"></el-table-column>
      <el-table-column prop="press" label="出版社"></el-table-column>
      <el-table-column width="80px" prop="count" label="当前数量"></el-table-column>
      <el-table-column width="190px" label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="editHandle(scope.row.id,true)">查看详情</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="text" @click="borrowHandle(scope.row.id)">借阅</el-button>
          <el-divider direction="vertical" v-if="hasAuth('book:manage:update')&&pagePerms.length>1"></el-divider>
          <el-button type="text" @click="editHandle(scope.row.id,false)" v-if="hasAuth('book:manage:update')">编辑
          </el-button>
          <el-divider direction="vertical" v-if="hasAuth('book:manage:delete')&&pagePerms.length>1"></el-divider>
          <el-popconfirm title="确定要删除这条记录吗？" @confirm="delHandle(scope.row.id)" v-if="hasAuth('book:manage:delete')">
            <el-button type="text" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!--页码-->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="current"
                   :page-sizes="[10, 20, 50, 100]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
                   :total="total"></el-pagination>

    <el-dialog title="书籍信息" :visible.sync="dialogFormVisible" width="600px">
      <p v-if="isBorrow" style="font-size: 20px">确定借阅该书籍吗？</p>
      <el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item label="书籍名称" prop="name" label-width="100px">
          <el-input :disabled="isBorrow" v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="ISBN码" prop="isbn" label-width="100px">
          <el-input :disabled="isBorrow" v-model="editForm.isbn" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="中文名" prop="cname" label-width="100px">
          <el-input :disabled="isBorrow" v-model="editForm.cname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="索书号" prop="callNumber" label-width="100px">
          <el-input :disabled="isBorrow" v-model="editForm.callNumber" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="作者" prop="author" label-width="100px">
          <el-input :disabled="isBorrow" v-model="editForm.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="译者" prop="translator" label-width="100px">
          <el-input :disabled="isBorrow" v-model="editForm.translator" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="类别" prop="typeId" label-width="100px">
          <el-select :disabled="isBorrow" v-model="editForm.typeId" filterable placeholder="请输入并选择图书类别">
            <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.typeName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="语种" prop="languages" label-width="100px">
          <el-input :disabled="isBorrow" v-model="editForm.languages" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出版社" prop="press" label-width="100px">
          <el-input :disabled="isBorrow" v-model="editForm.press" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="书籍数量" prop="total" label-width="100px">
          <el-input :disabled="isBorrow" type="number" v-model="editForm.total" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editForm')">取 消</el-button>
        <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>

    <el-drawer
        :title="editForm.name"
        :visible.sync="drawer"
        @before-close="resetForm(editForm)">


      <p class="drawer-p" v-if="editForm.cname">
        <strong>中文名：</strong>
        <span>{{ editForm.cname }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.isbn">
        <strong>ISBN码：</strong>
        <span>{{ editForm.isbn }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.callNumber">
        <strong>索书号：</strong>
        <span>{{ editForm.callNumber }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.author">
        <strong>作者：</strong>
        <span>{{ editForm.author }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.translator">
        <strong>译者：</strong>
        <span>{{ editForm.translator }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.typeName">
        <strong>类别：</strong>
        <span>{{ editForm.typeName }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.press">
        <strong>出版社：</strong>
        <span>{{ editForm.press }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.languages">
        <strong>语种：</strong>
        <span>{{ editForm.languages }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.count">
        <strong>当前数量：</strong>
        <span>{{ editForm.count }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.total">
        <strong>总数量：</strong>
        <span>{{ editForm.total }}</span>
      </p>
      <p class="drawer-p" v-if="editForm.brokenCount">
        <strong>破损数量：</strong>
        <span>{{ editForm.brokenCount }}</span>
      </p>
    </el-drawer>
  </div>
</template>
<script>
import qs from "qs";

export default {
  name: "Book",
  data() {
    return {
      //搜索框表单
      searchForm: {name: null},
      //编辑表单
      editForm: {},
      //编辑表单规则
      editFormRules: {
        name: [{required: true, message: '请输入书籍名称', trigger: 'blur'}],
        isbn: [{required: true, message: '请输入ISBN码', trigger: 'blur'}],
        callNumber: [{required: true, message: '请输入索书号', trigger: 'blur'}],
        author: [{required: true, message: '请输入书籍作者', trigger: 'blur'}],
        typeId: [{required: true, message: '请选择书籍类型', trigger: 'blur'}],
        press: [{required: true, message: '请输入出版社', trigger: 'blur'}],
        languages: [{required: true, message: '请输入书籍语种', trigger: 'blur'}],
        total: [{required: true, message: '请输入总数量', trigger: 'blur'}],
      },
      //当前页，默认为1
      current: 1,
      //记录总数，默认为0
      total: 0,
      //每页记录数，默认每页10条
      size: 10,
      //是否显示编辑/新增dialog
      dialogFormVisible: false,
      //表格数据
      tableData: [],
      //当前页需要的权限列表，只包括按钮类型
      pagePerms: [],
      //选中的行数组
      multipleSelection: [],
      //是否选择记录，如果否则禁用批量删除按钮
      delBtnStu: true,
      //是否显示抽屉
      drawer: false,
      options: [],
      isBorrow: false
    }
  },
  methods: {
    borrowHandle(id) {

      this.isBorrow = true;
      this.editHandle(id, false);
    },
    select() {
      this.current = 1;
      this.getList();
    },
    saveHandle() {
      this.resetForm('editForm');
      this.$axios.get('/type/list').then(res => {
        this.options = res.data.data;
      });
      this.dialogFormVisible = true
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(rows) {
      this.multipleSelection = rows;
      this.delBtnStu = rows.length === 0
    },
    getList() {
      this.$axios.get('/book', {
        params: {
          name: this.searchForm.name,
          current: this.current,
          size: this.size
        }
      }).then(res => {
        this.tableData = res.data.data
        this.total = res.data.total
      })
    },
    handleSizeChange(val) {
      this.size = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.current = val
      this.getList()
    },
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: 'loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          if (!this.isBorrow) {
            this.$axios({
              method: this.editForm.id ? 'put' : 'post',
              url: '/book',
              data: this.editForm
            }).then(res => {
              loading.close();
              this.resetForm(formName)
              this.$message({
                showClose: true, message: '恭喜你，操作成功', type: 'success', duration: 2000, onClose: () => {
                  this.getList()
                }
              });
            })
          } else {

            this.$axios.post("/borrowRecord/userBorrow", {
              bookId: this.editForm.id,
              bookPeriodical: 0,
            }).then((res) => {
              loading.close();
              this.resetForm(formName)
              this.$message({
                showClose: true, message: '恭喜你，借阅成功', type: 'success', duration: 2000, onClose: () => {
                  this.getList()
                }
              });
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    editHandle(id, isDrawer) {
      const loading = this.$loading({
        lock: true,
        text: 'loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.resetForm('editForm');
      this.$axios.get('/type/list').then(res => {
        this.options = res.data.data;
      });
      this.$axios.get("/book/info/" + id).then(res => {
        loading.close();
        this.editForm = res.data.data
        if (isDrawer) {
          this.drawer = true;
        } else {
          this.dialogFormVisible = true
        }
      })
    },
    delHandle(id) {
      let ids = []
      id ? ids.push(id) : this.multipleSelection.forEach(row => {
        ids.push(row.id)
      })

      this.$axios.delete("/book", {
        params: {
          ids: ids,
        },
        paramsSerializer: params => {
          return qs.stringify(params, {indices: false})
        }
      }).then(res => {
        this.$message({
          showClose: true, message: '恭喜你，操作成功', type: 'success', duration: 2000, onClose: () => {
            this.getList()
          }
        });
      })
    },
    resetForm(formName) {
      this.dialogFormVisible = false
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this.editForm = {}
    },
  },
  created() {
    this.getList();
    this.pagePerms = this.getPagePerms(this.$route.name);
  }
}
</script>

<style scoped>
.el-pagination {
  float: right;
  margin-top: 20px;
  padding-bottom: 30px;
}

.drawer-p {
  margin-left: 20px;
}
</style>
